<template>
  <div class="table-main">
    <el-dialog
      :close-on-click-modal="false"
      @close="handMyClose"
      :append-to-body="true"
      title="单页管理"
      :visible.sync="dialogVisible1"
      width="60%"
    >
      <div style="margin-top:50px;" v-loading="loading2">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="单页信息" name="first">
            <el-form ref="form" :model="form" label-width="120px">
              <el-row :gutter="20" justify="center" type="flex">
                <el-col :span="16">
                  <el-upload
                    class="upload-demo"
                    action
                    drag
                    :auto-upload="false"
                    :show-file-list="false"
                    :on-change="changeUpload"
                  >
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">点击上传</div>
                    <div class="el-upload__tip">支持绝大多数图片格式，单张图片最大支持5MB</div>
                  </el-upload>
                </el-col>
              </el-row>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="详情录入" name="second">
            <myTinymce ref="ceshifuwenben"></myTinymce>
          </el-tab-pane>
        </el-tabs>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible1 = false">取 消</el-button>
        <el-button
          type="primary"
          @click="handFromSub('form')"
          v-if="isShow!=3"
          :loading="bntLoading"
        >确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="图片剪裁" :visible.sync="dialogVisible33" append-to-body>
      <div class="cropper-content">
        <div class="cropper" style="text-align:center">
          <!-- <vueCropper
            ref="cropper"
            :img="option.img"
            :outputSize="option.size"
            :outputType="option.outputType"
            :info="true"
            :full="option.full"
            :canMove="option.canMove"
            :canMoveBox="option.canMoveBox"
            :original="option.original"
            :autoCrop="option.autoCrop"
            :fixed="option.fixed"
            :fixedNumber="option.fixedNumber"
            :centerBox="option.centerBox"
            :infoTrue="option.infoTrue"
            :fixedBox="option.fixedBox"
          ></vueCropper>-->
        </div>
        <img :src="imgCeshi" alt />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="finish">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { imgSizi } from '@/utils/myUtils'
import myTinymce from '@/components/Tinymce'
export default {
  name: 'SidebarLogo',
  components: {
    myTinymce
  },
  watch: {
    isState(newObj) {
      this.isShow = newObj
    }
  },
  props: {
    isState: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      imgCeshi: '',
      dialogVisible33: false,
      loadingUploda2: false,
      bntLoading: false,
      headers: {
        token: localStorage.getItem('mytoken') || ''
      },
      option: {
        img: '', // 裁剪图片的地址
        info: true, // 裁剪框的大小信息
        outputSize: 0.8, // 裁剪生成图片的质量
        outputType: 'jpeg', // 裁剪生成图片的格式
        canScale: false, // 图片是否允许滚轮缩放
        autoCrop: true, // 是否默认生成截图框
        // autoCropWidth: 300, // 默认生成截图框宽度
        // autoCropHeight: 200, // 默认生成截图框高度
        fixedBox: false, // 固定截图框大小 不允许改变
        fixed: false, // 是否开启截图框宽高固定比例
        fixedNumber: [7, 5], // 截图框的宽高比例
        full: true, // 是否输出原图比例的截图
        canMoveBox: true, // 截图框能否拖动
        original: false, // 上传图片按照原始比例渲染
        centerBox: false, // 截图框是否被限制在图片里面
        infoTrue: true // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
      },
      picsList: [],
      loadingUploda: false,
      defaultParams: {
        label: 'title',
        value: 'id',
        children: 'children'
      },
      form: { goodTypeId: '' },
      shopStatusOptions: [],
      isShow: 0,
      imageUrl: '',
      dialogImageUrl: '',
      dialogVisible1: false,
      addressKeyword: '',
      activeName: 'first',
      dialogVisible: false,
      brandList: [],
      goodClassList: [],
      findAllsList: [],
      loading2: true,
      companyList: []
    }
  },
  async mounted() {
    // this.$api.getGoodsListl().then(res => {
    //   this.shopStatusOptions = res.data.data
    // })

    this.companyList = (await this.$api.getFindCompany()).data.data
    console.log(this.companyList, '单位')
  },
  methods: {
    changeUpload(file, fileList) {
      const isLt5M = file.size / 1024 / 1024 < 5
      this.fileinfo = file
      console.log(file, 'file.url')

      // 上传成功后将图片地址赋值给裁剪框显示图片
      this.$nextTick(() => {
        this.option.img = URL.createObjectURL(file.raw)
        this.dialogVisible33 = true
      })
    },
    finish() {
      this.$refs.cropper.getCropData(data => {
        // do something
        console.log(data)
        this.imgCeshi = data
      })
    },
    handData(val) {
      console.log(this.form.goodTypeId, val)
    },
    async handGetList(val) {
      this.activeName = 'first'
      this.loading2 = false
      this.brandList = (await this.$api.getSysBrand()).data.data

      this.$refs.ceshifuwenben.init2()
      this.findAllsList = (await this.$api.userByShop()).data.data
      console.log('商家当店铺', this.findAllsList)
      let newData = (await this.$api.getGoodsTypeTreeinfo()).data.data

      newData.forEach(item => {
        if (item.children.length == 0) {
          item.disabled = true
        }
      })
      this.goodClassList = this.getTreeData(newData)
      console.log(this.goodClassList, 'this.goodClassList')
      if (val == 1) {
        this.$refs.ceshifuwenben.setContent('')
      }
    },
    handGetShop(id) {
      this.$forceUpdate()
      this.loading2 = true
      this.$api.getSysSelectGoodsByIdGoods(id).then(async res => {
        console.log('详情吗', res.data.data)
        res.data.data.shops = parseInt(res.data.data.shops)
        res.data.data.resourcesList.forEach(item => {
          item.url = item.resPath
        })
        await this.$refs.ceshifuwenben.init()
        this.$refs.ceshifuwenben.setContent(res.data.data.details)
        this.form = res.data.data
        this.form.goodTypeId = this.form.goodTypeId + ''
        this.loading2 = false
      })
    },
    onChange() {
      this.loadingUploda2 = false
    },
    handSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw)
      console.log(res, '==')
      this.loadingUploda = false
      var url = JSON.parse(res.message)
      this.$set(this.form, 'mainImg', url.url)
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      const isJPG = file.type === 'image/jpeg'
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      const isSize = imgSizi(file, 378, 378)
      return isSize
    },
    handMyClose() {
      this.$refs.ceshifuwenben.Myremove()
      // this.$refs.form.resetFields()
      for (let key in this.form) {
        this.form[key] = ''
      }
      this.$refs.ceshifuwenben.fwbObj = ''
      this.form.resourcesList = []
    },
    handFromSub(formName) {
      this.$refs.ceshifuwenben.getContent()
      this.form.shopStatus = 1
      this.form.details = this.$refs.ceshifuwenben.fwbObj
      this.form.goodAttributeList = null

      //1编辑
      if (this.isState == 1) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            this.bntLoading = true

            if (typeof this.form.goodTypeId == 'string') {
            } else {
              this.form.goodTypeId = this.form.goodTypeId[
                this.form.goodTypeId.length - 1
              ]
            }
            console.log('编辑', this.form)
            let shop = this.form

            if (!this.$refs.ceshifuwenben.fwbObj) {
              this.$message({
                message: '请录入商品详情'
              })
              this.activeName = 'second'
              console.log(
                this.$refs.ceshifuwenben.fwbObj,
                'this.$refs.ceshifuwenben.fwbObj'
              )
              return
            }
            this.form.resourcesList.forEach(item => {
              delete item.url
              item.fromType = 2
            })
            this.$api
              .getSysEditGoods(this.form)
              .then(res => {
                this.dialogVisible1 = false
                this.bntLoading = true
                this.$parent.init()

                this.$refs.ceshifuwenben.init()
                this.$message({
                  message: res.data.message,
                  type: 'success'
                })
              })
              .finally(() => {
                this.bntLoading = false
              })
          } else {
            console.log('error submit!!')
            this.$message({
              message: '请完成表单录入'
            })
            this.activeName = 'first'
            this.bntLoading = false
            return false
          }
        })
      } else if (this.isState == 0) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            if (!this.$refs.ceshifuwenben.fwbObj) {
              this.$message({
                message: '请录入商品详情'
              })
              this.activeName = 'second'
              console.log(
                this.$refs.ceshifuwenben.fwbObj,
                'this.$refs.ceshifuwenben.fwbObj'
              )
              return
            }
            this.bntLoading = true
            // this.form.goodTypeId = this.form.goodTypeId[0]
            if (typeof this.form.goodTypeId == 'string') {
            } else {
              this.form.goodTypeId = this.form.goodTypeId[
                this.form.goodTypeId.length - 1
              ]
            }
            this.form.resourcesList.forEach(item => {
              item.fromType = 2
            })
            let shop = this.form
            this.$api
              .getSysAddGoods(this.form)
              .then(res => {
                console.log(res, '添加商品', this.form)
                this.bntLoading = false
                this.dialogVisible1 = false
                this.$parent.init()
                this.$refs.form.resetFields()
                this.$refs.ceshifuwenben.init()
                this.$message({
                  message: res.data.message,
                  type: 'success'
                })
              })
              .finally(() => {
                this.bntLoading = false
              })
          } else {
            console.log('error submit!!')
            this.$message({
              message: '请完成表单录入'
            })
            this.activeName = 'first'
            return false
          }
        })
      }
    },

    // handSuccess(response, file, fileList) {
    //   console.log(response, file, fileList, '成功回调')
    //   this.form.shopImg = response.message
    // },
    handSuccess2(res, file, fileList) {
      this.loadingUploda2 = false
      if (fileList[0].response == undefined) {
        this.form.resourcesList.push({
          resPath: JSON.parse(res.message).url,
          url: JSON.parse(res.message).url,
          imagePurpose: 1,
          isDelete: 2,
          resType: 1
        })
      } else {
        if (this.form.resourcesList == undefined) this.form.resourcesList = []
        this.form.resourcesList.push({
          resPath: JSON.parse(res.message).url,
          url: JSON.parse(res.message).url,
          imagePurpose: 1,
          isDelete: 2,
          resType: 1
        })
      }
    },
    beforeAvatarUpload2(file) {
      this.loadingUploda2 = true
      const isLt2M = file.size / 1024 / 1024 < 2
      const isJPG = file.type === 'image/jpeg'
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      const isSize = imgSizi(file, 750, 750)
      isSize
        .then(res => {})
        .catch(err => {
          this.loadingUploda2 = false
        })
      return isSize
    },
    handleRemove(file, fileList) {
      console.log(fileList, '?????????', file, this.form.resourcesList)
      if (fileList.length == 0) {
        this.form.resourcesList = []
        return
      }
      if (fileList[0].response == undefined) {
        this.form.resourcesList = fileList
      } else {
        this.form.resourcesList = []
        fileList.forEach(item => [
          this.form.resourcesList.push({
            resPath: JSON.parse(file.response.message).url,
            url: JSON.parse(file.response.message).url,
            imagePurpose: 1,
            isDelete: 2,
            resType: 1
          })
        ])
      }
      console.log(this.form.resourcesList, 'chengg')
    },
    handlePictureCardPreview(file, fileList) {
      console.log(file, fileList)
    },
    handleClose() {
      this.dialogVisible = false
    },
    handMapShow() {
      this.dialogVisible = true
    },
    handleClick() {},
    getTreeData(data) {
      // 循环遍历json数据
      for (var i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          data[i].children = undefined
        } else {
          this.getTreeData(data[i].children)
        }
      }

      return data
    }
  }
}
</script>

<style lang="scss" scoped>
.cropper-content {
  .cropper {
    width: auto;
    height: 300px;
  }
}
.img_item_box {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  img {
    margin-right: 8px;
    margin-bottom: 8px;
    border-radius: 6px;
  }
}
.map_btn {
  width: 82px;
  height: 22px;
  background: rgba(56, 173, 147, 1);
  border-radius: 4px;
  color: #fff;
  font-size: 14px;
  line-height: 22px;
  text-align: center;
  margin-top: 8px;
}
/deep/ .el-form-item__label {
  font-size: 14px;
  color: #000;
  font-weight: bold;
}
.form_box {
  width: 80%;
  margin: 0 auto;
}
.avatar-uploader /deep/ .el-upload {
  border: 1px dashed #38ad93;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #38ad93;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
